package controller.user.user;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.VO.UserLoginVO;
import model.entity.User;
import service.Impl.UserServiceImpl;
import util.GetJsonUtil;
import util.JwtUtils;
import util.ResultUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/user/login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User u= (User) GetJsonUtil.get(req,new User());
        UserServiceImpl us=new UserServiceImpl();
        String json;
        UserLoginVO ul=us.login(u.getUsername(),u.getPassword());
        if(ul.getName()!=null){
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",ul.getId());
            String jwt= JwtUtils.generateJwt(claims);
            ul.setToken(jwt);
            System.out.println(ul);
            json= ResultUtil.getJSON(ul,"登陆成功");
        }
        else json= ResultUtil.getJSON(null,"账号或密码错误");
        resp.getWriter().println(json);
    }
}
